import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { timer } from 'rxjs';

import { RouterStateService, LockScreenService, LockScreenState } from '@core/base';
import { fnCheckForm } from '@util/form';
import { NzModalRef } from 'ng-zorro-antd/modal';

import { PasswordFormComponent } from './password-form.component';

@Component({
  selector: 'app-lock',
  templateUrl: './lock.component.html'
})
export class LockComponent implements OnInit {
  @ViewChild('pwdForm')
  pwdForm!: PasswordFormComponent;
  lockScreenState!: LockScreenState;

  constructor(
    private router: Router,
    private modal: NzModalRef,
    private routerStateSrc: RouterStateService,
    private lockScreenSrc: LockScreenService
  ) {}

  ngOnInit(): void {}

  onLock(): void {
    if (fnCheckForm(this.pwdForm.form)) {
      return;
    }

    const pwdInput = this.pwdForm.password;
    this.lockScreenSrc.publish({ locked: true, password: pwdInput?.value });
    this.closeForm();
  }

  onGoBack(): void {
    this.closeForm();
    timer(100).subscribe(() => this.router.navigateByUrl(this.routerStateSrc.previouRouter));
  }

  closeForm(): void {
    this.modal.destroy();
  }
}
